<template>
  <a-table
    :columns="columns"
    :rowKey="rowKey"
    :row-selection="rowSelection"
    :data-source="dataSource"
    :pagination="paginations"
    :loading="loading"
    :scroll="scroll"
    @change="handleTableChange"
  >
    <template #headerCell="{ column }">
      <span>{{t(column.title)}}</span>
    </template>
    <template #bodyCell="{ column, record, index }">
      <template v-if="column.dataIndex === 'index'">{{ index + 1 }}</template>
      <template v-else-if="column.type === 'money'">{{ Money(record[column.dataIndex] || 0.0) }}</template>
      <template v-else-if="column.slot">
        <slot :name="column.slot" :row="record" :index="index" :data="dataSource"></slot>
      </template>
    </template>
  </a-table>
</template>

<script setup lang="ts">
import { defineProps, defineEmits, reactive, computed } from 'vue';
import { Pagination, Scroll } from './fe-table.type';
import type { TableColumnsType } from 'ant-design-vue';
import { Money } from '@/utils/util';
import {useI18n} from "vue-i18n";

const {t} = useI18n();

export interface Props {
  columns: TableColumnsType;
  dataSource: any;
  pagination?: Pagination;
  loading?: boolean;
  scroll?: Scroll;
  defaultSelectedRowKeys?: string[];
  rowKey?: string;
  selection?: boolean;
}

const defaultPagination = reactive({
  size: 'small',
  pageSize: '10',
  total: 0,
  showTotal: () => `共 ${defaultPagination.total} 条`,
  showSizeChanger: true,
  pageSizeOptions: ['10', '20', '30', '40', '50','100','200'],
});

const props = withDefaults(defineProps<Props>(), {
  loading: true,
  scroll: () => ({ y: '53vh' }),
  rowKey: 'id',
});

const paginations = computed(() => Object.assign(defaultPagination, props.pagination));

const emits = defineEmits(['changePage', 'selectionChange']);

const handleTableChange = (val: any) => emits('changePage', val);

const rowSelection = computed(() => ({
  onChange: (selectedRowKeys: any, selectedRows: any) => emits('selectionChange', { selectedRowKeys, selectedRows }),
  getCheckboxProps: (record: any) => ({ disabled: record.disabled }),
  selectedRowKeys: props.defaultSelectedRowKeys,
}));

</script>

<style lang="less" scoped></style>
